#!/bin/bash
#
# 得到2403next、master工程的最新包列表，并更新OBS的相应工程。基于已git clone的openeuler/release-management
#
# 要求在~/obs目录下执行，目录下有各个工程的目录

if [ ! -d ~/obs/release-management ]; then
	echo "error: git clone https://gitee.com/openeuler/release-management first"
	exit 1
fi

branchs="openEuler-24.03-LTS-Next openEuler-25.09 master"
# branch ==> project
declare -A projs projsepol
projs=([openEuler-24.03-LTS-Next]=openEuler:24.03:Next
       [openEuler-25.09]=openEuler:25.09
       [master]=openEuler:Master)
projsepol=([openEuler-24.03-LTS-Next]=openEuler:24.03:Next:Epol
       [openEuler-25.09]=openEuler:25.09:Epol
       [master]=openEuler:Master:Epol)

for p in ${projs[*]} ${projsepol[*]}; do
	if [ ! -d $p ]; then
		echo "error: project $p must exist in ~/obs"
		exit 2
	fi
done

namepat='[^[:blank:]]+'

export VC_REALNAME=laokz

# working in project directory
addpkg()
{
	local proj=$1
	local branch=$2
	local pkg=$3

        osc mkpac $pkg >/dev/null
        cd $pkg
        cat >_service <<eof
<services>
        <service name="tar_scm">
                <param name="scm">git</param>
                <param name="url">git@gitee.com:src-openeuler/$pkg.git</param>
                <param name="revision">$branch</param>
                <param name="exclude">*</param>
                <param name="extract">*</param>
        </service>
</services>
eof
        osc add _service >/dev/null
        osc commit -n >/dev/null
	cd ..
}

# working in ~/obs directory
adddel()
{
	local oldlist=$1
	local newlist=$2
	local proj=$3
	local branch=$4

	cd $proj

	while read line; do
		if [[ "$line" =~ ^\<\ ($namepat) ]]; then
			osc rdelete -m "release change" $proj ${BASH_REMATCH[1]}
			echo "deleted $proj ${BASH_REMATCH[1]}"
		elif [[ "$line" =~ ^\>\ ($namepat) ]]; then
			addpkg $proj $branch ${BASH_REMATCH[1]}
			echo "added $proj ${BASH_REMATCH[1]}"
		fi
	done <<< $(diff $oldlist $newlist)

	cd ~/obs
}

# 更新包列表
cd ~/obs/release-management
git pull >/dev/null
for b in $branchs; do
	# 备份老列表
	mv -f ~/obs/list.$b ~/obs/.list.$b
	mv -f ~/obs/list.${b}epol ~/obs/.list.${b}epol

	if [ "$b" != "master" ]; then
		cat $b/baseos/pckg-mgmt.yaml $b/everything-exclude-baseos/pckg-mgmt.yaml |grep -E '^- name:'|cut -f3 -d' '|sort -s > ~/obs/list.$b
		grep -E '^- name:' $b/epol/pckg-mgmt.yaml |cut -f3 -d' '|sort -s > ~/obs/list.${b}epol
	else
		dirs=`ls -d master/openEuler*|grep -v -E openEuler-Epol\|openEuler-Factory`
		for d in $dirs; do
			cat $d/pckg-mgmt.yaml >>~/obs/__z
		done
		sed 's/\r//' ~/obs/__z |grep -E '^- name:'|cut -f3 -d' '|sort -s > ~/obs/list.$b
		rm -f ~/obs/__z
		grep -E '^- name:' master/openEuler-Epol/pckg-mgmt.yaml |cut -f3 -d' '|sort -s|sed 's/\r//' > ~/obs/list.${b}epol
	fi
done

# 增减OBS工程包
cd ~/obs
for b in $branchs; do
	adddel ~/obs/.list.$b ~/obs/list.$b ${projs[$b]} $b
	adddel ~/obs/.list.${b}epol ~/obs/list.${b}epol ${projsepol[$b]} $b
done

